import { GetConfig, OpenDirectory, OpenFile, UpdateConfig } from "@app";
import { main } from "@model";
import { Button, Form, Input, Space, notification } from "antd";
import { useEffect, useState } from "react";

export default function ConfigStorage() {
  const [config] = Form.useForm()
  const [configData, setConfigData] = useState(new main.Config())

  const selectFile = async () => {
    let path = await OpenFile()
    config.setFieldValue('dbPath', path)
    configData.dbPath = path
  }

  const selectDirectory = async () => {
    let directory = await OpenDirectory()
    config.setFieldValue('attachmentPath', directory)
    configData.attachmentPath = directory
  }

  const onValuesChange = (changeValues: any, allValues: any) => {
    setConfigData(allValues)
  }

  const saveConfig = () => {
    UpdateConfig(configData).then(() => {
      notification.success({
        message: '修改成功',
        description: '成功',
        placement: 'bottomRight',
      })
    }).catch(e => {
      notification.error({
        message: '修改失败',
        description: e,
        placement: 'bottomRight',
      })
    })
  }

  const syncConfigInfo = async () => {
    await GetConfig().then(c => {
      setConfigData(c)
      config.setFieldsValue(c)
    })
  }

  useEffect(() => {
    syncConfigInfo()
  }, []);

  return <>
    <Form
      form={config}
      onValuesChange={onValuesChange}
    >
      <Form.Item label="数据库" name='dbPath'>
        <Input addonAfter={
          <div style={{ cursor: 'pointer' }} onClick={selectFile} >···</div>
        }
        />
      </Form.Item>

      <Form.Item label="附件路径" name='attachmentPath'>
        <Input addonAfter={
          <div style={{ cursor: 'pointer' }} onClick={selectDirectory} >···</div>
        }
        />
      </Form.Item>

      <Form.Item>
        <Button onClick={saveConfig} type='primary'>保存</Button>
      </Form.Item>
    </Form >
  </>
}
